import React, { useState } from 'react'
import { Card, Button, Space, Typography, message, Divider } from 'antd'
import { 
  FilePdfOutlined, 
  FileExcelOutlined, 
  FileTextOutlined, 
  DownloadOutlined,
  ExportOutlined
} from '@ant-design/icons'
import { StoryboardData, StoryboardScene, ShotType, CameraAngle, CameraMovement } from '../../../types/document'
import { 
  StoryboardExportDialog,
  ExportType,
  exportToPDF,
  exportToExcel,
  exportToText,
  exportToMarkdown
} from '../../components/StoryboardExport'

const { Title, Text } = Typography

/**
 * 分镜导出功能测试面板
 * 用于测试所有导出功能
 */
export const StoryboardExportTestPanel: React.FC = () => {
  const [exportDialogVisible, setExportDialogVisible] = useState(false)
  const [testStoryboard, setTestStoryboard] = useState<StoryboardData | null>(null)
  const [exporting, setExporting] = useState(false)

  // 创建测试分镜数据
  const createTestStoryboard = (): StoryboardData => {
    const scenes: StoryboardScene[] = [
      {
        id: 'scene_1',
        title: '开场介绍',
        description: '主持人开场白，介绍今天的主题内容',
        order: 0,
        shot: {
          type: ShotType.MEDIUM,
          angle: CameraAngle.EYE_LEVEL,
          movement: CameraMovement.STATIC
        },
        timing: {
          duration: 15
        },
        sceneLocation: {
          name: '演播室主舞台',
          type: 'interior' as any,
          lighting: 'artificial_bright' as any
        },
        elements: {
          characters: [
            { id: 'host1', name: '主持人张三', role: 'main' as const }
          ],
          props: [
            { id: 'desk1', name: '主持台', importance: 'featured' as const },
            { id: 'screen1', name: '背景大屏', importance: 'background' as const }
          ]
        },
        audioElements: {},
        visual: {},
        production: {
          priority: 'high' as const,
          complexity: 'simple' as const,
          requiredCrew: ['摄像师', '灯光师', '音响师']
        },
        attachments: {}
      },
      {
        id: 'scene_2',
        title: '产品特写',
        description: '展示产品的各个角度和细节特征',
        order: 1,
        shot: {
          type: ShotType.CLOSE_UP,
          angle: CameraAngle.SLIGHTLY_HIGH,
          movement: CameraMovement.ZOOM_IN
        },
        timing: {
          duration: 20
        },
        sceneLocation: {
          name: '产品展示台',
          type: 'interior' as any,
          lighting: 'artificial_bright' as any
        },
        elements: {
          characters: [],
          props: [
            { id: 'product1', name: '主要产品', importance: 'featured' as const },
            { id: 'bg1', name: '白色背景', importance: 'background' as const }
          ]
        },
        audioElements: {},
        visual: {},
        production: {
          priority: 'normal' as const,
          complexity: 'medium' as const,
          requiredCrew: ['摄像师', '灯光师']
        },
        attachments: {}
      },
      {
        id: 'scene_3',
        title: '专家访谈',
        description: '邀请行业专家进行深度访谈讨论',
        order: 2,
        shot: {
          type: ShotType.WIDE,
          angle: CameraAngle.EYE_LEVEL,
          movement: CameraMovement.PAN_LEFT
        },
        timing: {
          duration: 180
        },
        sceneLocation: {
          name: '访谈区域',
          type: 'interior' as any,
          lighting: 'natural_day' as any
        },
        elements: {
          characters: [
            { id: 'host1', name: '主持人张三', role: 'main' as const },
            { id: 'expert1', name: '专家李四', role: 'guest' as const }
          ],
          props: [
            { id: 'sofa1', name: '访谈沙发', importance: 'featured' as const },
            { id: 'table1', name: '茶几', importance: 'background' as const }
          ]
        },
        audioElements: {},
        visual: {},
        production: {
          priority: 'high' as const,
          complexity: 'complex' as const,
          requiredCrew: ['摄像师A', '摄像师B', '灯光师', '音响师', '导播']
        },
        attachments: {}
      },
      {
        id: 'scene_4',
        title: '结束语',
        description: '总结要点，感谢观众，预告下期内容',
        order: 3,
        shot: {
          type: ShotType.MEDIUM,
          angle: CameraAngle.EYE_LEVEL,
          movement: CameraMovement.STATIC
        },
        timing: {
          duration: 12
        },
        sceneLocation: {
          name: '演播室主舞台',
          type: 'interior' as any,
          lighting: 'artificial_bright' as any
        },
        elements: {
          characters: [
            { id: 'host1', name: '主持人张三', role: 'main' as const }
          ],
          props: [
            { id: 'desk1', name: '主持台', importance: 'featured' as const }
          ]
        },
        audioElements: {},
        visual: {},
        production: {
          priority: 'normal' as const,
          complexity: 'simple' as const,
          requiredCrew: ['摄像师', '灯光师']
        },
        attachments: {}
      }
    ]

    return {
      scenes,
      totalDuration: scenes.reduce((total, scene) => total + scene.timing!.duration, 0),
      videoFormat: {
        aspectRatio: '16:9' as any,
        resolution: '1920x1080' as any,
        frameRate: 25,
        colorSpace: 'Rec709'
      },
      shootingPlan: {
        estimatedBudget: 50000,
        requiredEquipment: [],
        shootingDays: 1,
        locations: ['演播室', '产品展示台', '访谈区域']
      }
    }
  }

  // 初始化测试数据
  const handleCreateTestData = () => {
    const storyboard = createTestStoryboard()
    setTestStoryboard(storyboard)
    message.success(`创建测试分镜数据成功！包含 ${storyboard.scenes.length} 个场景，总时长 ${storyboard.totalDuration} 秒`)
    console.log('[导出测试] 创建测试数据:', storyboard)
  }

  // 快速导出测试
  const handleQuickExport = async (type: ExportType) => {
    if (!testStoryboard) {
      message.warning('请先创建测试数据')
      return
    }

    setExporting(true)
    try {
      let result
      const projectTitle = '测试分镜脚本项目'

      switch (type) {
        case ExportType.PDF:
          result = await exportToPDF(testStoryboard, projectTitle)
          break
        case ExportType.EXCEL:
          result = await exportToExcel(testStoryboard, projectTitle)
          break
        case ExportType.TEXT:
          result = await exportToText(testStoryboard, projectTitle)
          break
        case ExportType.MARKDOWN:
          result = await exportToMarkdown(testStoryboard, projectTitle)
          break
      }

      if (result.success) {
        message.success(`${type.toUpperCase()} 导出成功！文件大小: ${(result.fileSize! / 1024).toFixed(1)} KB`)
        console.log(`[导出测试] ${type} 导出成功:`, result)
      } else {
        message.error(`导出失败: ${result.error}`)
        console.error(`[导出测试] ${type} 导出失败:`, result.error)
      }
    } catch (error) {
      message.error(`导出过程中发生错误: ${error}`)
      console.error(`[导出测试] ${type} 导出错误:`, error)
    } finally {
      setExporting(false)
    }
  }

  // 打开高级导出对话框
  const handleAdvancedExport = () => {
    if (!testStoryboard) {
      message.warning('请先创建测试数据')
      return
    }
    setExportDialogVisible(true)
  }

  return (
    <Card title="分镜导出功能测试面板" size="small" style={{ marginBottom: '16px' }}>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        {/* 测试数据管理 */}
        <div>
          <Title level={5}>测试数据</Title>
          <Space wrap>
            <Button type="primary" onClick={handleCreateTestData}>
              创建测试分镜数据
            </Button>
            {testStoryboard && (
              <Text type="success">
                ✓ 已创建测试数据：{testStoryboard.scenes.length} 个场景，
                总时长 {testStoryboard.totalDuration} 秒
              </Text>
            )}
          </Space>
        </div>

        <Divider />

        {/* 快速导出 */}
        <div>
          <Title level={5}>快速导出测试</Title>
          <Space wrap>
            <Button
              icon={<FilePdfOutlined />}
              onClick={() => handleQuickExport(ExportType.PDF)}
              loading={exporting}
              disabled={!testStoryboard}
            >
              导出PDF
            </Button>
            
            <Button
              icon={<FileExcelOutlined />}
              onClick={() => handleQuickExport(ExportType.EXCEL)}
              loading={exporting}
              disabled={!testStoryboard}
            >
              导出Excel
            </Button>
            
            <Button
              icon={<FileTextOutlined />}
              onClick={() => handleQuickExport(ExportType.TEXT)}
              loading={exporting}
              disabled={!testStoryboard}
            >
              导出文本
            </Button>
            
            <Button
              icon={<FileTextOutlined />}
              onClick={() => handleQuickExport(ExportType.MARKDOWN)}
              loading={exporting}
              disabled={!testStoryboard}
            >
              导出Markdown
            </Button>
          </Space>
        </div>

        <Divider />

        {/* 高级导出 */}
        <div>
          <Title level={5}>高级导出选项</Title>
          <Space>
            <Button
              type="primary"
              icon={<ExportOutlined />}
              onClick={handleAdvancedExport}
              disabled={!testStoryboard}
            >
              打开导出对话框
            </Button>
            <Text type="secondary">支持完整的导出选项配置</Text>
          </Space>
        </div>

        {/* 测试说明 */}
        <div style={{ fontSize: '12px', color: '#666' }}>
          <Title level={5}>测试说明：</Title>
          <ul style={{ margin: 0, paddingLeft: '20px' }}>
            <li>先点击"创建测试分镜数据"生成测试用的分镜场景</li>
            <li>使用快速导出按钮测试各种格式的导出功能</li>
            <li>使用高级导出测试完整的导出选项和配置</li>
            <li>查看浏览器下载文件夹确认导出的文件</li>
            <li>检查控制台输出了解详细的导出过程日志</li>
          </ul>
        </div>
      </Space>

      {/* 导出对话框 */}
      {testStoryboard && (
        <StoryboardExportDialog
          visible={exportDialogVisible}
          storyboardData={testStoryboard}
          projectTitle="测试分镜脚本项目"
          onClose={() => setExportDialogVisible(false)}
        />
      )}
    </Card>
  )
}

export default StoryboardExportTestPanel